package client.fx;

import java.net.URL;
import java.util.ResourceBundle;

import client.socket.SocketClient;
import javafx.application.Platform;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.text.Text;

public class ClientController implements Initializable {

	@FXML
	private TextArea sendArea = new TextArea("");// 发送框
	@FXML
	private Button sendBtn = new Button();// 发送按钮
	@FXML
	private TextArea receArea = new TextArea();// 接收框
	@FXML
	private Button connBtn = new Button();// 连接按钮
	@FXML
	private Button closeBtn = new Button();// 关闭按钮
	@FXML
	private Text tipLabel = new Text();// 提示框

	private SocketClient socketClient;
	private SimpleStringProperty receMsg = new SimpleStringProperty();// 接收的消息
	private SimpleIntegerProperty isConnected = new SimpleIntegerProperty(0);// 连接标志

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		socketClient = new SocketClient(receMsg, isConnected);
		sendArea.textProperty().addListener(e -> {// 监听发送框
			if (sendArea.getText().trim().equals("")) {
				sendBtn.setDisable(true);
			} else {
				sendBtn.setDisable(false);
			}
		});
		receMsg.addListener(e -> {
			receArea.setText(receArea.getText() + receMsg.get() + "\n");
		});
		sendBtn.setDisable(true);
		closeBtn.setDisable(true);
		connBtn.setDisable(false);
		sendArea.setDisable(true);
		tipLabel.setText("Unconnected");
		isConnected.addListener(e -> {
			if (isConnected.get() == 0) {// 未连接
				sendBtn.setDisable(true);
				closeBtn.setDisable(true);
				connBtn.setDisable(false);
				sendArea.setDisable(true);
				tipLabel.setText("Unconnected");
			} else if (isConnected.get() == 1) {// 连接成功
				closeBtn.setDisable(false);
				sendArea.setDisable(false);
				connBtn.setDisable(true);
				tipLabel.setText("Success connected");
			} else {// 连接中
				closeBtn.setDisable(true);
				sendArea.setDisable(true);
				connBtn.setDisable(true);
				tipLabel.setText("Try to connecting...");
			}
		});

	}

	@FXML
	private void sendBtnOnAction(ActionEvent e) {
		socketClient.sendMesssage(sendArea.getText());
	}

	@FXML
	private void connBtnOnAction(ActionEvent e) {
		Platform.runLater(() -> {
			socketClient.connect();
		});
	}

	@FXML
	private void closeBtnOnAction(ActionEvent e) {
		Platform.runLater(() -> {
			socketClient.close();
		});
	}

}
